//引入依赖
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cors = require('cors');

//搭建web服务器
var app = express();


//配置中间件
app.use(cors({
  "origin":["http://localhost:8848","http://127.0.0.1:8848",'http://localhost:8080'],//,','http://localhost:8080''
  "credentials":true,
  "methods":"GET,HEAD,PUT,PATCH,POST,DELETE",
  "allowedHeaders":["token"]



}))
app.set('views', path.join(__dirname, 'views'));//配置模板路径
app.set('view engine', 'ejs');//引擎采用ejs
app.use(logger('dev'));//日志格式
app.use(express.json());//非地址栏中间件
app.use(express.urlencoded({ extended: false }));

let multer  = require('multer');

// let objMulter = multer({ dest: './public/upload' }); //dest: 指定 保存位置（存到服务器)

let storage = multer.diskStorage({

  destination: function (req, file, cb) {

    if(req.url.indexOf('user') !== -1 || req.url.includes('reg')){
      cb(null, path.join(__dirname,'public','upload','user'))
    }else if(req.url.includes('banner')){
      cb(null, path.join(__dirname,'public','upload','banner'))
    }else{
      cb(null, path.join(__dirname,'public','upload','product'))
    }
    
  }
})

let objMulter = multer({ storage }); //dest: 指定 保存位置（存到服务器)
app.use(objMulter.any());  //允许上传什么类型文件,any 代表任何类型 


//资源托管
app.use(express.static(path.join(__dirname, 'public','template')));
app.use('/admin',express.static(path.join(__dirname, 'public','admin')));
app.use(express.static(path.join(__dirname, 'public')));


//响应 安装路由 任务分发

//管理端
//客户端
app.all('/api/*',require('./utils/params'))
app.use('/api/login',require('./routes/api/login'))
app.use('/api/reg',require('./routes/api/reg'))
app.use('/api/user',require('./routes/api/user'))
app.use('/api/news',require('./routes/api/news'))

//代理端


// 处理错误
app.use(function(req, res, next) {
  next(createError(404));
});
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);

  if(req.url.includes('/api')){// 用户端接口不存在 返回  {err:1,msg:'不存在的接口'}
    res.send({err:1,msg:'不存在的接口'})
  }else if(req.url.includes('/admin')){// 管理端接口不存在 返回  res.render('error.ejs')
    res.render('error');
  }else{ // 资源托管没有对应的页面 返回 404.html
    // res.sendFile(path.join(__dirname,'public','template','index.html'))
  }
  
});

module.exports = app;
